import tkinter as tk
from tkinter import simpledialog, messagebox, ttk


class ChainDialog(simpledialog.Dialog):
    # 添加类变量保存上次选择的状态
    last_shape = "chain"
    last_description = ""
    last_color = "#00FF00"  # 初始默认颜色（与原代码默认颜色一致）

    def __init__(self, parent, title=None, colors=None):
        self.colors = colors if colors else ["#00FF00", "#0000FF", "#FF0000"]
        super().__init__(parent, title)

    def body(self, master):
        tk.Label(master, text="Shape:").grid(row=0, sticky="w", pady=(5, 0))
        # 使用上次保存的shape初始化
        self.shape = tk.StringVar(value=ChainDialog.last_shape)

        shapes = ["cand", "cell", "digit", "chain", "result"]
        shape_option = tk.OptionMenu(master, self.shape, *shapes)
        shape_option.grid(row=0, column=1, sticky="w", pady=(5, 0))

        tk.Label(master, text="Description:").grid(row=1, sticky="w", pady=(5, 0))
        self.description = tk.Text(master, width=100, height=15)
        # 插入上次保存的描述内容
        self.description.insert("1.0", ChainDialog.last_description)
        self.description.grid(row=1, column=1, pady=(5, 0))

        self.color_label = tk.Label(master, text="Color:", foreground=self.colors[0])
        self.color_label.grid(row=2, sticky="w", pady=(5, 0))

        # 使用上次保存的color初始化
        self.color = tk.StringVar(value=ChainDialog.last_color)
        color_option = tk.OptionMenu(master, self.color, *self.colors)
        color_option.grid(row=2, column=1, sticky="w", pady=(5, 0))

        self.color.trace_add("write", self.color_changed)

        return self.description

    def apply(self):
        # 用户点击确定按钮时保存当前状态
        shape = self.shape.get()
        description = self.description.get("1.0", tk.END).strip()
        color = self.color.get()
        # 更新类变量保存最新状态
        ChainDialog.last_shape = shape
        ChainDialog.last_description = description
        ChainDialog.last_color = color
        self.result = (shape, description, color)

    def color_changed(self, *args):
        selected_color = self.color.get()
        # print(self.colors, self.color_label)
        self.color_label.config(foreground=selected_color)


def open_chain_dialog():
    colors = [
        "#0096FF",
        "#00FA92",
        "#FF9300",
        "#FF40FF",
        "#0355F1",
        "#00F900",
        "#945200",
        "#9437FF",
    ]

    dialog = ChainDialog(root, colors=colors)
    if dialog.result:
        shape, description, color = dialog.result
        messagebox.showinfo("Result", f"{shape}\n{description}\n{color}")


if __name__ == "__main__":
    root = tk.Tk()
    root.title("Drawing Tool Example")
    root.geometry("400x300")

    button = tk.Button(root, text="Open Drawing Dialog", command=open_chain_dialog)
    button.pack(pady=50)

    root.mainloop()
